<template>
  <div class="min-h-screen bg-base-100">
    <div v-if="post" class="blog-container">
      <!-- 返回按钮 -->
      <div class="mb-6">
        <RouterLink to="/blog" class="btn btn-outline btn-sm gap-2">
          <icon-arrow-left class="w-4 h-4" />
          返回列表
        </RouterLink>
      </div>
      
      <!-- 文章封面 -->
      <div v-if="post.coverImage" class="mb-8">
        <img 
          :src="post.coverImage" 
          :alt="post.title" 
          class="w-full h-64 md:h-96 object-cover rounded-lg" />
      </div>
      
      <!-- 文章标题 -->
      <h1 class="text-4xl font-bold mb-4">{{ post.title }}</h1>
      
      <!-- 文章元信息 -->
      <div class="flex items-center gap-4 mb-8">
        <div class="text-base-content/70">
          <span>{{ formatDate(post.publishedAt) }}</span>
          <span class="mx-2">•</span>
          <span>{{ post.author }}</span>
        </div>
        
        <!-- 编辑按钮 -->
        <div class="ml-auto">
          <RouterLink :to="`/editor/${post.id}`" class="btn btn-sm btn-outline gap-2">
            <icon-pencil class="w-4 h-4" />
            编辑
          </RouterLink>
        </div>
      </div>
      
      <!-- 标签 -->
      <div v-if="post.tags.length" class="flex flex-wrap gap-2 mb-8">
        <span 
          v-for="tagId in post.tags" 
          :key="tagId" 
          class="badge badge-outline">
          {{ getTagName(tagId) }}
        </span>
      </div>
      
      <!-- 文章内容 -->
      <div class="prose prose-lg max-w-none mb-12">
        <div v-if="useMarkdown" v-html="renderedContent"></div>
        <div v-else v-html="post.content"></div>
      </div>
      
      <hr class="my-12 border-base-300" />
      
      <!-- 相关文章 -->
      <div v-if="relatedPosts.length" class="mb-12">
        <h3 class="text-2xl font-bold mb-6">相关文章</h3>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div v-for="relatedPost in relatedPosts" :key="relatedPost.id" 
               class="card bg-base-100 shadow-md card-hover">
            <div class="card-body">
              <h4 class="card-title">
                <RouterLink :to="`/blog/${relatedPost.id}`">
                  {{ relatedPost.title }}
                </RouterLink>
              </h4>
              <p>{{ relatedPost.excerpt || truncateContent(relatedPost.content) }}</p>
              <div class="card-actions justify-end">
                <RouterLink :to="`/blog/${relatedPost.id}`" class="btn btn-sm btn-primary">
                  阅读全文
                </RouterLink>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载提示 -->
    <div v-else-if="loading" class="blog-container py-16 text-center">
      <div class="loading loading-spinner loading-lg"></div>
      <p class="mt-4">加载中...</p>
    </div>
    
    <!-- 404 页面 -->
    <div v-else class="blog-container py-16 text-center">
      <icon-file-question class="w-24 h-24 mx-auto text-base-300" />
      <h2 class="text-2xl font-bold mt-6">文章不存在</h2>
      <p class="mt-4">文章可能已被删除或链接有误</p>
      <div class="mt-8">
        <RouterLink to="/blog" class="btn btn-primary">
          返回博客列表
        </RouterLink>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useBlogStore } from '@/stores/blogStore';
import { useSettingsStore } from '@/stores/settingsStore';
import type { BlogPost } from '@/types';
import { marked } from 'marked';

const route = useRoute();
const router = useRouter();
const blogStore = useBlogStore();
const settingsStore = useSettingsStore();

const loading = ref(true);
const postId = computed(() => route.params.id as string);

// 判断是否使用 Markdown 渲染
const useMarkdown = computed(() => settingsStore.editorType === 'markdown');

// 获取文章
const post = computed(() => {
  const foundPost = blogStore.getPostById(postId.value);
  loading.value = false;
  return foundPost;
});

// 渲染 Markdown 内容
const renderedContent = computed(() => {
  if (!post.value || !useMarkdown.value) return '';
  return marked(post.value.content);
});

// 获取相关文章（相同标签的其他文章）
const relatedPosts = computed(() => {
  if (!post.value) return [];
  
  // 获取相同标签的文章
  const postsWithSameTag = post.value.tags.length > 0
    ? blogStore.getPublishedPosts.filter(p => 
        p.id !== post.value?.id && 
        p.tags.some(tag => post.value?.tags.includes(tag))
      )
    : [];
  
  // 如果没有相同标签的文章，返回最新的文章
  if (postsWithSameTag.length === 0) {
    return blogStore.getPublishedPosts
      .filter(p => p.id !== post.value?.id)
      .slice(0, 3);
  }
  
  return postsWithSameTag.slice(0, 3);
});

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// 获取标签名称
const getTagName = (tagId: string) => {
  const tag = blogStore.getTagById(tagId);
  return tag ? tag.name : '';
};

// 截断内容
const truncateContent = (content: string): string => {
  if (content.length <= 100) return content;
  return content.substring(0, 100) + '...';
};

// 如果文章不存在，等待加载完成后重定向
onMounted(() => {
  setTimeout(() => {
    if (!loading.value && !post.value) {
      // 可以选择不重定向，而是在页面上显示文章不存在的提示
      // router.push('/blog');
    }
  }, 500);
});
</script> 